#!/usr/bin/env python3
import requests
import json
import sys

class CacheClient:
    def __init__(self, server_url):
        self.server_url = server_url.rstrip('/')
        self.headers = {'Content-Type': 'application/json; charpost=utf-8'}

    def post(self, key, value):
        """设置缓存值"""
        try:
            response = requests.post(
                self.server_url + '/',
                json={key: value},
                headers=self.headers
            )
            if response.status_code == 200:
                data = response.json()
                print(f"post successful: {data}")
                return True
            else:
                print(f"Error: {response.status_code} - {response.text}")
                return False
        except Exception as e:
            print(f"Error postting value: {e}")
            return False

    def get(self, key):
        """获取缓存值"""
        try:
            response = requests.get(
                self.server_url + f'/{key}',
                headers=self.headers
            )
            if response.status_code == 200:
                data = response.json()
                print(f"Value: {data}")
                return data[key]
            elif response.status_code == 404:
                print(f"Key '{key}' not found")
                return None
            else:
                print(f"Error: {response.status_code} - {response.text}")
                return None
        except Exception as e:
            print(f"Error getting value: {e}")
            return None

    def delete(self, key):
        """删除缓存值"""
        try:
            response = requests.delete(
                self.server_url + f'/{key}',
                headers=self.headers
            )
            if response.status_code == 200:
                data = response.json()
                print(f"Deleted: {data['deleted']} item(s)")
                return data['deleted']
            else:
                print(f"Error: {response.status_code} - {response.text}")
                return 0
        except Exception as e:
            print(f"Error deleting value: {e}")
            return 0

def print_usage():
    print("Usage:")
    print("  python client.py <server_port> post <key> <value>")
    print("  python client.py <server_port> get <key>")
    print("  python client.py <server_port> delete <key>")
    print("Example:")
    print("  python client.py 9527 post foo bar")
    print("  python client.py 9527 get foo")
    print("  python client.py 9527 delete foo")

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print_usage()
        sys.exit(1)

    server_port = sys.argv[1]
    command = sys.argv[2].lower()
    server_url = f'http://127.0.0.1:{server_port}'

    client = CacheClient(server_url)

    if command == 'post':
        if len(sys.argv) != 5:
            print("Usage: python client.py <port> post <key> <value>")
            sys.exit(1)
        key = sys.argv[3]
        value = sys.argv[4]
        client.post(key, value)
    elif command == 'get':
        if len(sys.argv) != 4:
            print("Usage: python client.py <port> get <key>")
            sys.exit(1)
        key = sys.argv[3]
        client.get(key)
    elif command == 'delete':
        if len(sys.argv) != 4:
            print("Usage: python client.py <port> delete <key>")
            sys.exit(1)
        key = sys.argv[3]
        client.delete(key)
    else:
        print("Invalid command. Use 'post', 'get', or 'delete'")
        print_usage()
